<template>
  <van-form @submit="onSubmit">
    <van-cell-group inset>
      <van-field
          v-model="userAccount"
          left-icon="contact"
          name="userAccount"
          label="账户"
          placeholder="请填写账户"
          :rules="[{ required: true, message: '请填写账户' }]"
      />
      <van-field
          v-model="userPassword"
          left-icon="setting"
          type="password"
          name="userPassword"
          label="密码"
          placeholder="请填写密码"
          :rules="[{ required: true, message: '请填写密码' }]"
      />
      <van-field
          v-model="userCode"
          center
          left-icon="setting"
          name="userPassword"
          label="验证码"
          placeholder="请填写验证码"
          :rules="[{ required: true, message: '请填写验证码' }]"
      >
        <template #left-icon>
          <svg t="1722673352128" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5044" id="mx_n_1722673352129"
               width="18" height="18">
            <path d="M943.1 172c-2.4-0.2-245.1-25.3-413.8-147.8-5.1-3.7-11-5.6-17.3-5.6-6.2 0-12.2 1.9-17.3 5.6C326.9 146 83.3 171.8 80.9 172c-15.2 1.4-26.6 14.1-26.6 29.3 0 6.7 0.6 165.8 54.8 344.4 32.1 105.8 76.4 196.4 131.9 269.2 70.3 92.3 158.5 156 262 189.2 2.9 0.9 5.9 1.4 9 1.4s6.1-0.5 8.9-1.4c103.6-33.2 191.7-96.8 262-189.2 55.4-72.7 99.8-163.2 131.9-269.2 54.1-178.6 54.8-337.7 54.8-344.4C969.7 186.1 958.3 173.5 943.1 172zM910.1 227.2l-0.1 1.6c-2.9 58.1-13.4 174.4-51.4 299.9-66.7 220.1-183.1 360.1-346 416.1L512 945l-0.6-0.2C349 888.9 232.7 749.4 165.8 530.1c-39.8-130.5-49.4-254.2-51.8-301.4l-0.1-1.6 1.5-0.2c70.6-10.3 250.5-44.8 395.5-142.4l0.9-0.7 1 0.7C658 182.1 837.9 216.6 908.5 227L910.1 227.2z" p-id="5045" fill="#000000"></path><path d="M641.8 351 467 580.3l-89-76.1c-5.3-4.5-12.1-7-19.1-7-8.6 0-16.8 3.7-22.4 10.3-10.5 12.3-9.1 31 3.3 41.5l112.7 96.4c5.2 4.4 12.4 7 19.6 7 0.9 0 1.8 0 2.7-0.1 8-0.8 15.4-5 20.3-11.4l193.7-254c4.8-6.3 6.8-14 5.7-21.8-1-7.8-5.1-14.7-11.3-19.5C670.1 335.6 651.6 338.1 641.8 351z" p-id="5046" fill="#000000"></path></svg>
        </template>
        <template #button>
          <van-image :src="verifyCodeImage" style="width: 90px;" @click="updateBaseImage"></van-image>
        </template>

      </van-field>
    </van-cell-group>

    <div style="
    color: #1677ff;
    font-size: 16px;
    display: flex;
    justify-content: space-between;
    margin-left: 30px;
    margin-right: 30px;
    ">
      <span>忘记密码？</span>
      <span @click="toRegister">注册</span>
    </div>


    <div style="margin: 16px;">
      <van-button round block type="primary" native-type="submit">
        登录
      </van-button>
    </div>
  </van-form>
</template>


<script setup lang="ts">
import {onMounted, ref} from "vue";
import {useRoute, useRouter} from "vue-router";
import {showToast} from "vant";
import {getLoginCodeByCaptcha, loginAccount} from "../../api/userApi.ts";
import {userStore} from "../../stores/user/user.ts";

const userAccount = ref('');
const userPassword = ref('');
const userCode = ref('');
const codePC = ref('');//存储服务端的验证码，不存放在redis了，这样一个页面就存放一个code就好了
const router = useRouter();
const route = useRoute();
const verifyCodeImage = ref('');
const verifyCodeKey = ref('');
const userStoreAPI = userStore();


console.log("redirect",route.query?.redirect);


const  onSubmit = async () => {
  // if (true){
  //   router.push('/index');
  //   return;
  // }

  //校验参数
  if (userAccount.value.length != 11){
    showToast("账户不正确");
    return;
  }
  if (userPassword.value.length < 8){
    showToast("账户不正确");
    return;
  }
  if (userCode.value == ''){
    showToast("请填写验证码");
    return;
  }
  if (userCode.value.length != 5){
    showToast("验证码不正确");
    return;
  }

  // 检验验证码是否正确
  if (userCode.value.toLowerCase() !== codePC.value.toLowerCase()) {
    showToast("验证码不正确");
    return;
  }

  const data = {
    userAccount: userAccount.value,
    userPassword: userPassword.value,
  };

  const res = await loginAccount(data);
  // 兼容新格式 code: 0 和旧格式 code: 200
  if (res.code === 0 || res.code === 200) {
    // 新格式：res.data.user，旧格式：res.data
    const userData = res.data?.user || res.data;
    //缓存用户信息
    userStoreAPI.setCurrentUser(userData);
    console.log("登录",userStoreAPI.currentUser);
    //判断是否是新注册的用户(是否选择了标签)
    if (userData.userStatus == 1){
      //跳转到选择标签页面
      router.push('/genderSelect');

    }else{
      // //直接重定向
      const redirectUrl = route.query?.redirect ?? '/index';//如果没有就默认时index首页
      if (redirectUrl === '/index') {
        router.replace('/index');
      } else {//redirectUrl == 'http://localhost:5173/user'
        if (typeof redirectUrl === "string") {
          window.location.href = redirectUrl + "";
        }
      }

    }


    //进行创建连接ws
    // initConnection();
    self.postMessage(`{"type":"initWS","value":${userData.id}}`);
  }else {
    showToast(res.data?.message);
    userPassword.value = '';
    userCode.value = '';
  }

};

//跳转到注册页面
const toRegister = ()=>{
  router.push('/register');
}

//登录页面的请求验证码图片
const getBaseImage = ()=>{
  getLoginCodeByCaptcha().then(res => {
    if (200 === res.code){
      verifyCodeImage.value = res.data?.verifyCode;
      verifyCodeKey.value = res.data?.verifyCodeKey;
      codePC.value = res.data?.code;
    }
  });
}
//点击后更新图片
const updateBaseImage = ()=>{
  getBaseImage();
}

onMounted(()=>{
  getBaseImage();
});

</script>



<style scoped>

</style>